package com.hqq.thread.tls;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.concurrent.Callable;

/**
 * DateFormatCallable
 * 使用SimpleDateFormat将string类型的日期转换成date类型的日期.日期格式和日期值通过构造函数传递给Callable.
 * 构造函数创建了SimpleDateFormat实例并且存储在一个ThreadLocal的实例变量中。
 * Created by heqianqian on 2017/7/2.
 */
public class DateFormatCallable implements Callable<Result> {

    private ThreadLocal<DateFormat> df;

    private String dateValue;

    public DateFormatCallable(String inDateFormat, String inDateValue) {
        final String dateFormat = inDateFormat;
        df = new ThreadLocal<DateFormat>() {
            @Override
            protected DateFormat initialValue() {
                return new SimpleDateFormat(dateFormat);
            }
        };
        this.dateValue = inDateValue;
    }

    @Override
    public Result call() throws Exception {
        System.out.println(Thread.currentThread() + " started executing...");
        Result result = new Result();
        for (int i = 1; i <= 5; i++) {
            try {
                result.getDateList().add(this.df.get().parse(this.dateValue));
            } catch (Exception e) {
                result.getExceptionList().add(e.getClass() + " " + e.getMessage());
            }
        }
        System.out.println(Thread.currentThread() + " finished processing part of the thread");
        return result;
    }
}
